package com.miyuan.wm.listener;

import com.miyuan.wm.data.UserInfo;
import com.miyuan.wm.service.SystemLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

@Slf4j
public class SessionListener extends SessionListenerAdapter {

	@Autowired
	private SystemLogService systemLogService;

	@Override
	public void onStart(Session session) {
		super.onStart(session);
	}

	@Override
	public void onStop(Session session) {
		super.onStop(session);
		sessionDestroyedLog(session);
	}

	@Override
	public void onExpiration(Session session) {
		super.onExpiration(session);
		sessionDestroyedLog(session);
	}

	/**
	 * 当 Shiro Session 被销毁时， 对已登陆的用户记录访问日志
	 *
	 * @param session 被销毁的 Session
	 */
	private void sessionDestroyedLog(Session session) {
		// 判断是否为已经登陆的用户, 判断依据是isAuthentication的值
		UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
		log.info("session销毁执行：{}", userInfo.toString());
		if (userInfo != null) {
			try {
				// 记录登出日志
				systemLogService.insertAccessRecord(userInfo.getUserID(), userInfo.getUserName(),
						userInfo.getAccessIP(), SystemLogService.ACCESS_TYPE_LOGOUT);
			} catch (Exception e) {
				log.error("异常", e);
			}
		}
	}
}
